import type { ChatCompletionCreateParamsStreaming } from "openai/resources";
import { createDiscreteApi } from "naive-ui";
import _ from "lodash";
export const useMessages = () => {
  const { chatMap, currentChat } = storeToRefs(chatStore());
  const { chatSettings } = storeToRefs(chatSettingStore());
  const { message } = createDiscreteApi(["message"]);
  const deleteMessage = (id: string | number) => {
    chatMap.value.get(currentChat.value)?.messages[id]?.controller?.abort?.();
    delete chatMap.value.get(currentChat.value)?.messages[id];
    if (
      ObjectToArray(chatMap.value.get(currentChat.value)!.messages)!.length ===
      0
    ) {
      chatMap.value.delete(currentChat.value);
      currentChat.value = 0;
    }
  };
  const stopMessage = (id: string | number) => {
    chatMap.value.get(currentChat.value)?.messages[id]?.controller?.abort?.();
    chatMap.value.get(currentChat.value)!.messages[id].status = "已停止";
  };
  const checkToMessage = () => {
    const apiUrl = chatSettings.value["api"].template["apiUrl"].value;
    const Authorization =
      chatSettings.value["api"].template["Authorization"].value;
    if (!apiUrl) {
      message.error("请先设置API地址");
      return false;
    }
    if (!Authorization) {
      message.error("请先设置API密钥");
      return false;
    }
    return true;
  };
  const retryMessage = (id: string | number) => {
    if (!checkToMessage()) return;
    const controller = new AbortController();
    const { chatSettings } = toRefs(chatSettingStore());
    const apiConfig = chatSettings.value["api"].template;
    const messageId = id;
    const messages: Message[] = ObjectToArray(
      chatMap.value.get(currentChat.value)!.messages
    )!;
    const index = messages.findIndex((item: any) => item.id === messageId);
    const request = messages.slice(0, index);
    chatMap.value.get(currentChat.value)!.messages[messageId!].content = "";
    chatMap.value.get(currentChat.value)!.messages[messageId!].status =
      "生成中";
    chatMap.value.get(currentChat.value)!.messages[messageId!].type = "newChat";
    chatMap.value.get(currentChat.value)!.messages[messageId!].controller =
      controller;
    openAPI<ChatCompletionCreateParamsStreaming>(
      apiConfig,
      request,
      (content: ExtendedChatCompletionChunk) => {
        const message = content.choices[0].delta.content;
        chatMap.value.get(currentChat.value)!.messages[messageId!].status =
          "生成中";
        chatMap.value.get(currentChat.value)!.messages[messageId!].role =
          "assistant";
        chatMap.value.get(currentChat.value)!.messages[messageId!].name = "AI";
        chatMap.value.get(currentChat.value)!.messages[messageId!].content +=
          message!;
        if (content.choices[0].finish_reason === "stop") {
          chatMap.value.get(currentChat.value)!.messages[messageId!].status =
            "已完成";
          return;
        }
        if (content.choices[0].finish_reason === "error") {
          chatMap.value.get(currentChat.value)!.messages[messageId!].status =
            "已失败";
          return;
        }
      },
      controller
    );
  };
  const { setChat, setCurrentChat, addChatMessages } = chatStore();

  const content = ref("");
  const appendMessagge = () => {
    if (!checkToMessage()) return;
    const message = content.value;
    content.value = "";
    if (!message.trim()) return;
    const { chatSettings } = toRefs(chatSettingStore());
    const apiConfig = chatSettings.value["api"].template;
    const baseConfig = chatSettings.value["base"].template;
    let youMessageId = "";
    if (currentChat.value === 0) {
      const chat = setChat();
      setCurrentChat(chat.id);
      youMessageId = addChatMessages(chat.id, {
        content: message,
        role: "user",
        name: baseConfig["username"].value,
        status: "已创建",
        type: "newChat",
      });
    } else {
      youMessageId = addChatMessages(currentChat.value, {
        content: message,
        role: "user",
        name: baseConfig["username"].value,
        status: "已创建",
        type: "newChat",
      });
    }
    const now_chat = currentChat.value;
    const controller = new AbortController();
    const messageId = addChatMessages(now_chat, {
      content: "",
      role: "assistant",
      status: "生成中",
      controller,
      type: "chat",
    });
    const request = _.cloneDeep(
      ObjectToArray<Message>(chatMap.value.get(now_chat)!.messages)!.filter(
        (e) => e.id !== messageId
      )
    );
    chatMap.value.get(now_chat)!.messages[messageId].type = "chat";
    chatMap.value.get(now_chat)!.messages[youMessageId].type = "chat";
    openAPI<ChatCompletionCreateParamsStreaming>(
      apiConfig,
      request,
      (content: ExtendedChatCompletionChunk) => {
        if (content.choices[0].finish_reason === "stop") {
          chatMap.value.get(now_chat)!.messages[messageId].status = "已完成";
          return;
        }
        if (content.choices[0].finish_reason === "error") {
          chatMap.value.get(now_chat)!.messages[messageId].status = "已失败";
          return;
        }
        const message = content.choices[0].delta.content;
        chatMap.value.get(now_chat)!.messages[messageId].content += message!;
      },
      controller
    );
  };
  return {
    appendMessagge,
    deleteMessage,
    stopMessage,
    retryMessage,
    content,
  };
};
